#include "animatedbackground.h"

#include <QPainter>

AnimatedBackground::AnimatedBackground(QWidget *parent) :
  QWidget(parent), _currentAnimation(NULL), _animationAlpha(1)
{
}

qreal AnimatedBackground::animationAlpha() const
{
  return _animationAlpha;
}

void AnimatedBackground::setBackground(const QString &path)
{
  delete _currentAnimation;
  _currentAnimation = NULL;
  if (_background.isNull())
  {
  _background = QPixmap(path);
    update();
  }
  else
  {
    _oldBackground = _background;
    _background = QPixmap(path);
    _currentAnimation = new QPropertyAnimation(this,"animationAlpha");
    _currentAnimation->setStartValue(0);
    _currentAnimation->setEndValue(1);
    _currentAnimation->setDuration(400);
    connect(_currentAnimation,SIGNAL(finished()),this,SLOT(animationFinished()));
    _currentAnimation->start(QAbstractAnimation::DeleteWhenStopped);
  }
}

void AnimatedBackground::setAnimationAlpha(qreal a)
{
  _animationAlpha = a;
  update();
}

void AnimatedBackground::animationFinished()
{
  _currentAnimation = NULL;
  _oldBackground = QPixmap();
}

void AnimatedBackground::paintEvent(QPaintEvent* ev)
{
  QPainter p(this);
  if (!_oldBackground.isNull())
  {
    p.setOpacity(1.-_animationAlpha);
    p.drawPixmap(0,0,width(),height(),_oldBackground);
    p.setOpacity(_animationAlpha);
    p.drawPixmap(0,0,width(),height(),_background);
  }
  else if (!_background.isNull())
  {
    p.drawPixmap(0,0,width(),height(),_background);
  }
  QWidget::paintEvent(ev);
}

